<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="username"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.trim="userage"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="usersex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addFn(editindex)">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(obj,index) in arr" :key="obj.id">
          <td>{{obj.id}}</td>
          <td>{{obj.username}}</td>
          <td>{{obj.userage}}</td>
          <td>{{obj.usersex}}</td>
          <td>
            <button @click="delFn(index)">删除</button>
            <button @click="edit(obj)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
// * 需求1: 铺设页面, 准备初始的数据(自己手写数据结构) - 前面是数组索引+1 *作为序号
// * 需求2: 当输入框没有值, 要给用户一个提示, 必须都有值才能增加新数据 (数据驱动页面哦)
// * 需求3: 添加功能 - 想好数据结构统一对象的key
// * 需求4: 点击编辑功能, 把值赋予到输入框上(不要操作dom, 数据驱动页面)
// * 需求5: 用户修改后, 点击相同按钮 - 想想怎么判断怎么是添加还是修改的功能 (提示: 准备一个全局变量, 点过编辑按钮可以让它为true) - 实现编辑后更新页面效果
// * 需求6: 点击删除, 删除这行数据
export default {
  data(){
    return {
      status:'add',
      username:"",
      userage:"",
      usersex:"",
      editindex:0,
      arr: JSON.parse(localStorage.getItem('info')) || []
    }
  },
  methods:{
    addFn(i){
      if(!this.username || !this.userage || !this.usersex) return alert('请填写完整的数据')
      if(this.status==='add') {
       this.arr.push({
         id:this.arr.length>0?this.arr[this.arr.length-1].id+1 : 1,
         username:this.username,
         userage:this.userage,
         usersex:this.usersex
      })
      localStorage.setItem('info',JSON.stringify(this.arr))
      this.username='',
      this.userage='',
      this.usersex=''
      }else{
        this.arr[i].username=this.username
        this.arr[i].userage=this.userage
        this.arr[i].usersex=this.usersex
        this.username='',
        this.userage='',
        this.usersex=''
        this.status='add'
      }
      
    },
    delFn(i){
           this.arr.splice(i,1)
    },
    edit(obj){
      this.status='edit'
      this.editindex=this.arr.indexOf(obj)
      this.username= obj.username
      this.userage= obj.userage
      this.usersex= obj.usersex
    }
  }
}
</script>
